<?php

namespace app\devices\service;

use think\admin\Service;
use think\App;
use think\cache\driver\Redis;

/**
 * 箱门数据服务
 * Class BoxService
 * @package app\data\service
 */
class VipService extends Service
{
    protected $redis;

    public function __construct(App $app)
    {
        $this->redis = new Redis();
        parent::__construct($app);
    }

    /**
     * 获取VIP信息
     * @param $id
     * @return array|mixed|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getVipInfo($id)
    {
        $vip = $this->redis->get("VIP_Info".$id)??[];
        $map['id'] = $id;
        if(!$vip){
            $vip = $this->app->db->name("jcg_vip_level")->where($map)->find();
            if($vip){
                $this->redis->set("VIP_Info".$id, $vip, 300);
            }
        }
        return $vip;
    }

    /**
     * 获取用户开通会员信息
     * @param $uid
     * @param int $is_show
     * @return array|mixed|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getUserVip($uid, $is_show=0){
        $map['user_id'] = $uid;
        $vipUser = $this->redis->get("VIP_User".$uid)??[];
        if($vipUser && $vipUser['end_time']>=time()){
            return $vipUser;
        }else if(empty($vipUser)){
            $vipUser = $this->app->db->name("jcg_vip_user")->where($map)->find();
            if($vipUser){
                $this->redis->set("VIP_User", $vipUser, $vipUser['end_time']-time());
                if($vipUser['end_time']>=time()){
                    return $vipUser;
                }
            }
        }
        if($is_show && $vipUser) {
            return $vipUser;
        }else{
            return [];
        }
    }

    public function setUserVip($uid, $days){
        $vipUser = $this->getUserVip($uid, 1);
        if($vipUser){
            $vipUser['star_time'] = $data['star_time'] = $vipUser['end_time']>time()?$vipUser['star_time']:time();
            $vipUser['end_time'] = $data['end_time'] = $vipUser['end_time']>time()?strtotime("+{$days} day", $vipUser['end_time']):strtotime("+{$days} day");
            $res = $this->app->db->name("jcg_vip_user")->where("id", $vipUser['id'])->update($data);
        }else{
            $vipUser['star_time'] = $data['star_time'] = time();
            $vipUser['end_time'] = $data['end_time'] = strtotime("+{$days} day");
            $vipUser['user_id'] = $data['user_id'] = $uid;

            $res = $this->app->db->name("jcg_vip_user")->insertGetId($data);
        }
        if($res){
            $vipUser['id'] = $vipUser['id']??$res;
            $this->redis->set("VIP_User", $vipUser, $vipUser['end_time']-time());
        }
    }

}